package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private ProvinceInfoMapper provinceInfoMapper;
    @Autowired
    private CityInfoMapper cityInfoMapper;
    @Autowired
    private DistrictInfoMapper districtInfoMapper;

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private RoomInfoMapper roomInfoMapper;
    /*
     *  1.修改
     *  2.添加
     * */
    @Override
    public void saveOrUpdateInfo(ApartmentSubmitVo apartmentSubmitVo) {
        Long id = apartmentSubmitVo.getId(); //公寓的id

        //查询公寓所属的省的信息(名字) 已知: provinceId
        ProvinceInfo provinceInfo = provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId());
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());

        //查询公寓所属的城市名字
        CityInfo cityInfo = cityInfoMapper.selectById(apartmentSubmitVo.getCityId());
         apartmentSubmitVo.setCityName(cityInfo.getName());

         //查询 公寓所属的区县名字
        DistrictInfo districtInfo = districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());



        //添加或者修改公寓的基本信息  insert into xxxxx : mybatisplus自动查询最新添加的主键值且把主键的值保存到 被添加的对象的id属性中
        this.saveOrUpdate(apartmentSubmitVo);
        //是否是修改
        if (id != null) { //是修改-> 先删除和当前公寓有关联的外键表信息  再添加最新的关联信息
            //删除公寓配套关系表信息
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,id));
            //删除公寓标签关系表信息
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,id));
            //删除公寓杂费关系表信息
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,id));
            //删除公寓图片表信息
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id).eq(GraphInfo::getItemType, ItemType.APARTMENT));
        }


        /*
        *   facilityInfoIds：[1,2,3]
        *   apartment_id:    9
        *
        *    9     1
        *    9     2
        *    9     3
        *
        * */
        //添加公寓配套关系表
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds(); //配套的id集合
        if(!CollectionUtils.isEmpty(facilityInfoIds)){
            List<ApartmentFacility> apartmentFacilities=new ArrayList<>();// 公寓和配套的关系实体对象集合
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility= ApartmentFacility.builder().apartmentId(apartmentSubmitVo.getId()).facilityId(facilityInfoId).build();
                apartmentFacilities.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }


        //添加公寓标签关系
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if(!CollectionUtils.isEmpty(labelIds)){
             List<ApartmentLabel> apartmentLabels=new ArrayList<>();
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel=ApartmentLabel.builder().apartmentId(apartmentSubmitVo.getId()).labelId(labelId).build();
                apartmentLabels.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabels);
        }

        //添加公寓杂费关系
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
         if(!CollectionUtils.isEmpty(feeValueIds)){
              List<ApartmentFeeValue> apartmentFeeValues=new ArrayList<>();
             for (Long feeValueId : feeValueIds) {

                 ApartmentFeeValue apartmentFeeValue=ApartmentFeeValue.builder().apartmentId(apartmentSubmitVo.getId()).feeValueId(feeValueId).build();
                  apartmentFeeValues.add(apartmentFeeValue);
             }
              apartmentFeeValueService.saveBatch(apartmentFeeValues);
         }

         //添加公寓的图片信息
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();

         if(!CollectionUtils.isEmpty(graphVoList)){
                List<GraphInfo> graphInfos=new ArrayList<>();
             for (GraphVo graphVo : graphVoList) {
                 GraphInfo graphInfo=new GraphInfo();

                 String url = graphVo.getUrl();

                 String fileName = url.substring(url.lastIndexOf("/")+1);
                 graphInfo.setName(fileName);
                 graphInfo.setUrl(graphVo.getUrl());
                 graphInfo.setItemId(apartmentSubmitVo.getId());
                 graphInfo.setItemType(ItemType.APARTMENT);
                 graphInfos.add(graphInfo);
             }
              graphInfoService.saveBatch(graphInfos);
         }




    }

    @Override
    public IPage<ApartmentItemVo> pageItem(Page<ApartmentItemVo> apartmentItemVoPage, ApartmentQueryVo queryVo) {

        return apartmentInfoMapper.pageItem(apartmentItemVoPage,queryVo);
    }


    /*
    *   回显的方法: 根据公寓的id查询公寓基本信息以及相关信息
    * */
    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        ApartmentDetailVo apartmentDetailVo=new ApartmentDetailVo();

        //查询公寓的基本信息
        ApartmentInfo apartmentInfo = this.getById(id);

        //查询公寓的配套信息
       List<FacilityInfo> facilityInfoList=  facilityInfoMapper.selectListByApartmentId(id);
       //查询公寓的标签
       List<LabelInfo> labelInfoList=   labelInfoMapper.selectListByApartmentId(id);
       //查询公寓的杂费信息
        List<FeeValueVo> feeValueVoList=feeValueMapper.selectListByApartmentId(id);
        //查询公寓的图片
        List<GraphVo> graphVoList=   graphInfoMapper.selectListByItemTypeAndItemId(id,ItemType.APARTMENT);


        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);

        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        apartmentDetailVo.setGraphVoList(graphVoList);

        return apartmentDetailVo;
    }

    @Override
    public void removeByIdInfo(Long id) {

        //查询当前被删除的公寓是否有房间 如果有房间提示不能删除
        Long count = roomInfoMapper.selectCount(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, id));
         if(count>0){
             //有房间,提示不能删除 抛自定义异常
            // throw  new LeaseException(ResultCodeEnum.DELETE_ERROR);
             throw  new LeaseException(208,"该公寓中有房间不能删除!!");
         }

         //删除公寓信息
         this.removeById(id);
         //删除当前公寓关联表的信息（图片，配套，标签，杂费）
        //删除公寓配套关系表信息
        apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,id));
        //删除公寓标签关系表信息
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,id));
        //删除公寓杂费关系表信息
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,id));
        //删除公寓图片表信息
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id).eq(GraphInfo::getItemType, ItemType.APARTMENT));

    }
}




